import configService from './config.service.js'
const baseUrl = configService.apiUrl
let requestType = "POST";
import jump from '../jump.js'

const getTokenStorage = () => {
	let token = ''
	try {
		token = uni.getStorageSync('newToken') || ''
	} catch (e) {
		console.log("getTokenStorage", token)
	}
	return token
}
// 拦截返回值
function requestStop(data) {
	if (data.code == 501) {
		uni.showToast({
			title: data.message ? data.message : '登录超时',
			icon: 'none'
		})
		setTimeout(function() {
			// uni.clearStorageSync()
			// #ifdef APP-PLUS
			//监听uni⼩程序发送的事件
			uni.sendHostEvent('login', {
				'token': getTokenStorage(),
				'from': ''
			}, (ret) => {
				//发送消息成功回调
				console.log('Send event to Host: ' + JSON.stringify(ret));
			});
			// #endif
			// #ifdef H5
			window.location.href = '/pages/login/login?from=' + window.location.href
			// #endif
			// #ifdef MP-WEIXIN
			uni.navigateTo({
				url: '/pages/login/login'
			})
			// #endif
		}, 2000)
	} else {
		if (data.url) {
			uni.showToast({
				title: data.message ? data.message : '提示信息',
				icon: 'none'
			})
			setTimeout(function() {
				// #ifdef H5
				window.location.href = "https://" + window.location.host + data.url
				// #endif
				// #ifndef H5
				jump.toJump(data.url)
				// #endif
			}, 2000)
			return false
		} else {
			return true
		}
	}
}

// post请求封装 可以传入methodType类型PUT
function request(url, data, methodType = "POST", status = false) {
	return new Promise((resolve, reject) => {
		let that = this;
		let requestData = {
			...data
		}
		// if (getTokenStorage()) {
		// 	requestData.jwt_token = getTokenStorage()
		// }
		if (status) {
			uni.showLoading({
				title: '加载中',
				icon: "none"
			});
		}
		uni.request({
			url: baseUrl + url,
			data: requestData,
			method: methodType,
			dataType: 'json',
			header: {
				// 'content-type': 'application/x-www-form-urlencoded',
				'content-type': 'application/json',
				// 'content-type': 'application/x-www-form-urlencoded',
				'X-Access-Token': getTokenStorage(),
			},
			success: function(res) {
				if (res) {
					switch (res.statusCode) {
						case 403:
							resolve('403，被禁止的');
							break;
						case 404:
							resolve('404，请求的资源不存在');
							break;
						case 500:
							resolve('500，内部服务器错误');
							break;
						default:
							if (requestStop(res.data)) {
								resolve(res.data);
							}
					}
				}
			},
			fail: function(e) {
				console.log(e, '#######################')
				reject('连接服务器失败!');
			},
			complete() {
				if (status) {
					uni.hideLoading()
				}
			}
		})
	});
}

// post请求封装 可以传入methodType类型PUT
function post(url, data, status = false) {
	return request(url, data, "POST", status)
}

// get请求封装
function get(url, data, status = false) {
	return request(url, data, "GET", status)
}

module.exports = {
	post,
	get
}